package data.content;

import java.io.IOException;

import network.e2e.FrameReader;
import network.e2e.FrameWriter;

/**
 * Parser from the net that can retrieve or send a corresponding object
 */

public class ContentParser {
  
  /**
   * Content IDs
   */
  private static final String CONTENT_SENTENCE = "CON_SENTENCE";
  private static final String CONTENT_STALKER_JOIN = "CON_STALKJOIN";
  private static final String CONTENT_STALKER_LEAVES = "CON_STALKLEAVE";
  
  /**
   * Decode a content from the network
   * @requires reader not null
   * @param reader the net
   * @return the content read
   * @throws IOException 
   */
  public static Content retrieve(FrameReader reader) throws IOException {
    assert (reader != null);
    String content_data = reader.readString();
    assert (content_data != null);
    if (content_data.equals(CONTENT_SENTENCE)) {
      return new ContentSentence(reader);
    } else if (content_data.equals(CONTENT_STALKER_JOIN)) {
      return new ContentStalkerJoin(reader);
    } else if (content_data.equals(CONTENT_STALKER_LEAVES)) {
      return new ContentStalkerLeaves(reader);
    } else {
      assert false :
        "ContentParser: Unrecognized Content ID";
      return null;
    }
  }
  
  /**
   * Encode a content to be sent over the network
   * @requires param not null
   * @param content the content
   * @param writer  the net
   * @throws IOException 
   */
  public static void send(Content content, FrameWriter writer) throws IOException {
    assert content != null && writer != null;
    
    if (content instanceof ContentSentence) {
      writer.writeString(CONTENT_SENTENCE);
    } else if (content instanceof ContentStalkerJoin) {
      writer.writeString(CONTENT_STALKER_JOIN);
    } else if (content instanceof ContentStalkerLeaves) {
      writer.writeString(CONTENT_STALKER_LEAVES);
    } else {
      assert false :
        "ContentParser: Unrecognized Content";
    }
    content.send(writer);
  }
  
}
